package com.salt.security.wechat.auth.service;

import com.salt.common.BusinessException;
import com.salt.common.ResponseStatus;
import com.salt.system.mapper.SysUserMapper;
import com.salt.system.model.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 微信or小程序密码登陆
 *
 * @author HaiBo Kuang
 * @date 2021年04月21日 下午 17:01
 */
@Service
public class WeChatPasswordLoginService {
    private final SysUserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public WeChatPasswordLoginService(@Lazy PasswordEncoder passwordEncoder,
                                      SysUserMapper userMapper) {
        this.passwordEncoder = passwordEncoder;
        this.userMapper = userMapper;
    }

    /**
     * 登陆行为
     *
     * @param userNameOrPhone 用户名or手机
     * @param pwd             密码
     */
    public Long login(String userNameOrPhone, String pwd) {
        SysUser query = new SysUser();
        query.setUserName(userNameOrPhone);
        SysUser sysUser = userMapper.selectOne(query);
        if (Objects.isNull(sysUser)) {
            query.setUserName(null);
            query.setPhone(userNameOrPhone);
            sysUser = userMapper.selectOne(query);
        }
        if (Objects.isNull(sysUser)) {
            throw new BusinessException(ResponseStatus.USER_NOT_FOUND);
        }
        if (!passwordEncoder.matches(pwd, sysUser.getPassword())) {
            throw new BusinessException(ResponseStatus.USERNAME_PASSWORD_INCORRECT);
        }
        return sysUser.getId();
    }

}
